package cn.dongqihong.framework.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5工具
 *
 * @author DongQihong
 */
public class MD5Util {

    /**
     * 加密字符串
     *
     * @param str 要加密的字符串
     * @return 加密后的32位密文, 加密失败返回原字符串.
     */
    public static String encrypt(String str) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(str.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            return str;
        } catch (UnsupportedEncodingException e) {
            return str;
        }
        byte[] byteArray = messageDigest.digest();
        StringBuffer md5StrBuff = new StringBuffer();
        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
                md5StrBuff.append("0").append(
                        Integer.toHexString(0xFF & byteArray[i]));
            else
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
        }
        return md5StrBuff.toString();
    }

    /**
     * 比较明文与密文
     *
     * @param plaintext  明文
     * @param ciphertext 密文
     * @return <code>true</code>密码匹配，<code>false</code>密码不匹配
     */
    public static boolean validate(String plaintext, String ciphertext) {
        return encrypt(plaintext).equals(ciphertext);
    }
}